﻿using CsvHelper.Configuration;
using log4net;
using Lottery.Classes;
using Lottery.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace Lottery.Data
{
    public class GiftData
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static GiftData instances = null;

        public static GiftData Instances
        {
            get
            {
                if (instances == null)
                    instances = new GiftData();
                return GiftData.instances;
            }
        }

        private GiftData()
        {
            if (gifts == null || gifts.Count <= 0)
            {
                gifts = this.loadGifts(MyResources.GetConfigPath(MyResources.GiftsName));
            }
        }

        private Dictionary<int, List<GiftInfo>> gifts = new Dictionary<int, List<GiftInfo>>();

        public Dictionary<int, List<GiftInfo>> Gifts
        {
            get { return gifts; }
            set { gifts = value; }
        }



        private int nowLevelIndex = 0;

        public int NowLevel
        {
            get { return levels[nowLevelIndex]; }
        }

        private int nowIndex = 0;

        public int NowIndex
        {
            get { return nowIndex; }
        }


        private int[] levels;

        public int[] Levels
        {
            get { return levels; }
        }
        //当前日期，sufei 2013/12/9
        private static DateTime dt = System.DateTime.Now;//获得今天的日期
        private TimeSpan ts1 = new TimeSpan(dt.Ticks);//将当前日期转化为可以比较的类型,sufei 2013/12/9

        private String nowDateStr = dt.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);

        private Dictionary<int, List<GiftInfo>> loadGifts(string fileName)
        {

            Dictionary<int, List<GiftInfo>> gifts = new Dictionary<int, List<GiftInfo>>();
            // List<String> wingift = this.loadWingifts(MyResources.GetConfigPath(MyResources.WinnersName));
            TxtData<GiftInfo> txtData = new TxtData<GiftInfo>(MyResources.GetConfigPath(MyResources.GiftsName));
            txtData.SkipLine = 3;
            txtData.ClassMap = typeof(GiftInfoMap);
            List<GiftInfo> allGiftInfos = txtData.readToObject();

            foreach (GiftInfo gift in allGiftInfos)
            {
                //从中奖名单中获取已经
                gift.OddNumber = gift.Number - WinnerData.Instances.existGift(gift.Name);
                if (String.IsNullOrEmpty(gift.EffectiveDate))
                {
                    gift.EffectiveDate = nowDateStr;
                }
                if (gift.OddNumber > 0 && gift.EffectiveDate.Equals(nowDateStr))
                {
                    gift.Number = gift.OddNumber;
                    if (gifts.ContainsKey(gift.Level))
                        gifts[gift.Level].Add(gift);
                    else
                        gifts.Add(gift.Level, new List<GiftInfo>() { gift });

                }
            }
            this.startIndex(gifts);//为gifts快速排序
            return gifts;
        }

        public sealed class GiftInfoMap : ClassMap<GiftInfo>
        {
            public GiftInfoMap()
            {
                Map(m => m.Level).Name("等级");
                Map(m => m.LevelName).Name("等级描述");
                Map(m => m.Name).Name("奖品");
                Map(m => m.Number).Name("数量");
                Map(m => m.Unit).Name("单位");
                //Map(m => m.Value).Name("价值");
                Map(m => m.OddNumber).Name("剩余");
                Map(m => m.EffectiveDate).Name("生效日期");
            }
        }

        private void startIndex(Dictionary<int, List<GiftInfo>> gifts)
        {
            this.levels = gifts.Keys.ToArray<int>();
                
            Sort.QuickSort(this.levels);
            //if (levels.Length > 0)
            //    this.nowLevelIndex = levels[0];
        }

        public GiftInfo RandomGift
        {
            get
            {
                if (this.levels.Length <= 0)
                    return null;
                if (nowLevelIndex >= this.levels.Length)
                    return null;
                try
                {
                    int index = this.RandomIndex(NowLevel);
                    if (this.gifts[NowLevel].Count <= 0)
                    {
                        nowLevelIndex++;
                    }
                    GiftInfo gift = this.gifts[NowLevel][index];// Dictionary<int, List<GiftInfo>> gifts
                    Console.WriteLine("抽取奖品{0}，等级{1}，剩余数量为{2}", gift.Name, gift.Level, gift.Number);
                    gift.GiftIndex = index;
                    return gift;

                }
                catch (Exception e)
                {
                    log.Error(e);
                    return null;
                }
            }
        }

        private int RandomIndex(int level)
        {
            int x = DateTime.Now.Millisecond * new Random(DateTime.Now.Millisecond).Next(1, 9);
            int count = this.gifts[level].Count > 0 ? this.gifts[level].Count - 1 : 0;
            int index = new Random(x).Next(0, count);
            return index;
        }

        //RandomStaff,无函数调用
        public GiftInfo RandomStaff(int level)
        {
            return this.gifts[level][this.RandomIndex(this.gifts[level].Count)];
        }

        /// <summary>
        /// 移除已经抽中的奖品
        /// </summary>
        /// <param name="level"></param>
        /// <param name="index"></param>
        public void removeGiftNum(GiftInfo giftInfo)
        {
            if (giftInfo.GiftIndex < 0)
                return;
            //剩余数量减掉
            giftInfo.OddNumber--;
            //数量减掉
            giftInfo.Number--;
            if (giftInfo.Number <= 0)
            {
                this.gifts[giftInfo.Level].RemoveAt(giftInfo.GiftIndex);
                Console.WriteLine("删除奖品信息{0}", giftInfo.Name);
            }
        }

    


    }
}
